<template>
  <div>
    <el-tree
      ref="treeRef"
      v-model="menuIds"
      :data="menuList"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      @check-change="handleCheckChange"
    />
  </div>
</template>

<script setup lang="ts">
import type { MenuTreeType } from '../type';

import { refreshDictOptions } from '#/hooks/useDictCache';
import { getTreeKeys } from '#/utils/gettreekeys';

const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
};
const menuList = ref<MenuTreeType[]>([]);
const menuIds = defineModel<number[]>('menuIds'); // 双向绑定
const menuHalfKeys = defineModel<number[]>('menuHalfKeys'); // 双向绑定
const treeRef = ref(); // 获取dom
const parendID = ref<number[]>([]); // 存在子项的父节点

// 选中节点事件
const handleCheckChange = () => {
  menuHalfKeys.value = treeRef.value?.getHalfCheckedKeys() || []; // 获取半选择的keys
  menuIds.value = treeRef.value?.getCheckedKeys() || []; // 获取选择节点的keys
};
onMounted(async () => {
  menuList.value = await refreshDictOptions('menu'); // 获取字典数据
  // 获取所有节点存在子节点的ID
  parendID.value = getTreeKeys(menuList.value, 'id') as number[];
});
// 数据回显更新
watch(
  () => menuIds.value,
  (val) => {
    // 去除所有的父节点ID，只保留子节点
    const newarr = val?.filter((item) => !parendID.value?.includes(item));
    treeRef.value?.setCheckedKeys(newarr); // 菜单下拉数据回显
  },
);
</script>
